import * as Cesium from '@cesiumjs';
import G3vViewer from "./viewer";
import {
  g3x_defineProperty,
  g3x_defineReadonly
} from "@g3x/utils";
import {
  defaultViews
} from "../defaultOptions";

/**
 * @param {Object} vm
 * @param {Object} viewersOptions viewers options
 * @param {Object} g3vOptions
 */
function g3v_viewers(viewersOptions, g3v) {
  const _this = this;
  const arrViewers = [];
  let mapViewers = {};

  viewersOptions.forEach((viewerOptions, i)=>{
    const g3vViewer = new G3vViewer(viewerOptions, g3v);
    arrViewers.push(g3vViewer)
    mapViewers[g3vViewer.name] = g3vViewer;

    g3x_defineReadonly(_this, g3vViewer.name, g3vViewer);
    g3v&&g3x_defineReadonly(g3v, `g3vViewer$${i+1}`, g3vViewer);
    g3v&&g3x_defineReadonly(g3v, `viewer$${i+1}`, g3vViewer.viewer);
  })

  _this.getByName = function(name){
    return mapViewers[name];
  }

  g3x_defineReadonly(_this, "size", ()=>arrViewers.length);

  _this.get = function(i){
    return arrViewers[i];
  }

  _this.destroy = function() {
    arrViewers.forEach(e=>e.destroy())
    arrViewers.splice(0)
    mapViewers = {}
  }
}

class G3vViewers {
  /**
   * @param {Object} vm
   * @param {Object} g3vOptions
   */
  constructor(g3vOptions, g3v) {
    console.log("G3vViewers constructor!")

    const viewers = new g3v_viewers(g3vOptions.viewers, g3v)
    g3x_defineReadonly(this, "g3vViewers", viewers);
    
    g3x_defineReadonly(this, "size", ()=>viewers.size);
    
    for(let i=0, n=viewers.size; i<n; ++i){
      const g3vViewer = viewers.get(i);
      g3x_defineReadonly(this, g3vViewer.name, g3vViewer);
    }
  }
  
  get(i){
    return this.g3vViewers.get(i)
  }

  destroy(){
    const {g3vViewers} = this;
    g3vViewers && g3vViewers.destroy()
  }
}

export default G3vViewers;
